import { defineStore } from 'pinia'
import { get } from '../utils/helper.js'
const shop = defineStore({
  id: 'shop',
  state: () => ({
    isReady: null,
    onReady: null,
    info: {},
    location: {
      lat: 0,
      lng: 0
    },
    cartList: []
  }),
	
  getters: {
    shopId: state => state.info?.id ?? 0
  },
  actions: {
    async init(obj = {}) {
      let id = obj.id || 0
      const lat = obj.lat || this.location.lat
      const lng = obj.lng || this.location.lng
      if (!id && !lat && !lng && uni.getStorageSync('shopId')) {
        id = uni.getStorageSync('shopId')
      }
      const { data } = await get('/Index/shop', { shop_id: id, lat, lon: lng })
      this.info = data
      uni.setStorageSync('shopId', data.id)
      typeof this.onReady === 'function' && this.onReady()
      return Promise.resolve({ info: data })
    },
    async cartLoad() {
      const res = await get('/Store/cart', { shop_id: this.shopId })
      this.cartList = res.data
      return Promise.resolve(res.data)
    }
  },
  // pinia 数据持久化处理，插件pinia-plugin-persist-uni
  persist: {
    enabled: false,
    strategies: [
      {
        key: 'shop-store'
      }
    ]
  }
})

export default shop
